<!--
  * 微信回复用户
-->
<template>
  <a-modal
    :width="1000"
    :open="openForm"
    @cancel="onReplyModalClose"
    :maskClosable="false"
    :destroyOnClose="true"
    @ok="onReplySubmit"
    :getContainer="getContainer"
    :footer="false"
  >
    <template #title>
      <div class="flex justify-between">
        <div>投诉详情</div>
        <div class="mr-12">
          <a-button @click="refresh" size="small">刷新</a-button>
        </div>
      </div>
    </template>
    <group-title class="pb-0.5">基本信息</group-title>
    <a-descriptions :column="2">
      <a-descriptions-item v-for="item in detailConfig[props.formSource]" :key="item.dataIndex" :label="item.label" v-bind="item.options">{{
        item?.customRender ? item.customRender(replyForm) : replyForm[item.dataIndex]
      }}</a-descriptions-item>
    </a-descriptions>
    <group-title class="pb-0.5">投诉内容</group-title>
    <a-descriptions :column="2">
      <template v-for="item in complaintConfig[props.formSource]">
        <a-descriptions-item
          :key="item.dataIndex"
          :label="item.label"
          v-bind="item.options"
          v-if="replyForm && replyForm.hasOwnProperty(item.dataIndex)"
        >
          <div v-if="item.dataIndex === 'images'">
            <component :is="getCustomRenderValue(item, replyForm)" />
          </div>
          <div v-else>
            {{ getCustomRenderValue(item, replyForm) }}
          </div>
        </a-descriptions-item>
      </template>
    </a-descriptions>
    <group-title class="py-2">交易信息</group-title>
    <OrderList :row-data="props.rowData" type="detail" @refresh="onReplyModalClose" />
    <group-title class="py-2">协商历史</group-title>
    <div v-if="props.formSource == 'ali'">
      青到登景支付宝商家平台进行童看协商历史
      <a-button type="primary" href="https://b.alipay.com/page/merchant-openplatform/securityCenter">链接</a-button>
    </div>
    <div v-else>
      <AliHistoryList :row-data="historyData" />
    </div>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch, getCurrentInstance, h } from 'vue'
  import { message, Modal, Upload, Image } from 'ant-design-vue'
  import { aliMiniHistory as aliMiniHistoryMerchant, aliDetail as aliDetailMerchant } from '/@/api/business/b-merchant/complaintManage'
  import { aliMiniHistory as aliMiniHistoryOperation, aliDetail as aliDetailOperation } from '/@/api/business/b-operation/complaintManage'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { getObjValue, setObjValue, formatToMoney, strToArr, selectDictLabel } from '/@/utils/common.js'
  import dayjs from 'dayjs'
  import AliHistoryList from './ali-history-list.vue'
  import OrderList from './order-list.vue'
  import { cloneDeep, isEmpty } from 'lodash-es'
  import {
    YES_OR_NO, //是否
    COMPLAINT_STATUS, //投诉状态
    COMPLAINT_SOURCE, //投诉来源
    COMPLAINT_PROBLEM_TYPE, //问题类型
  } from '/@/constants/dict'

  import { useUserStore } from '/@/store/modules/system/user'
  const USER_TYPE = useUserStore().userType // 用户类型: 1-平台;2-代理;4-商户
  // console.log('operation', useUserStore().loginType)

  const { proxy } = getCurrentInstance()

  const apiSource = {
    alimini: (data) => {
      if (USER_TYPE == '4') return aliMiniHistoryMerchant(data)
      if (USER_TYPE == '1') return aliMiniHistoryOperation(data)
    },
    ali: (data) => {
      if (USER_TYPE == '4') return aliDetailMerchant(data)
      if (USER_TYPE == '1') return aliDetailOperation(data)
    },
  }

  // ------------------------ 事件 ------------------------
  const getContainer = () => {
    return document.getElementById('smartAdminLayoutContent')
  }
  function getCustomRenderValue(item, replyForm) {
    if (typeof item.customRender === 'function') {
      return item.customRender(replyForm)
    }
    return replyForm[item.dataIndex]
  }

  const detailConfig = ref({
    alimini: [
      {
        label: '投诉订单号',
        dataIndex: 'complainId',
      },
      {
        label: '商户名称',
        dataIndex: 'merchantName',
      },
      {
        label: '交易金额',
        dataIndex: 'tradeAmount',
        // customRender: (data) => formatToMoney(data.amount / 100),
      },
      {
        label: '退款金额',
        dataIndex: 'refundAmount',
        // customRender: (data) => formatToMoney(data.refundAmount / 100),
      },
      {
        label: '投诉时间',
        dataIndex: 'gmtCreate',
        customRender: (data) => dayjs(data.gmtCreate).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        label: '投诉完结时间',
        dataIndex: 'gmtFinished',
        customRender: (data) => dayjs(data.gmtFinished).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        label: '过期时间',
        dataIndex: 'overdueTime',
        customRender: (data) => dayjs(data.overdueTime).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        label: '通道类型',
        dataIndex: 'channelTypes',
        customRender: () => {
          return proxy.$smartEnumPlugin.getDescByValue('ZZB_CHANNEL_TYPE_ENUM', props.rowData?.channelTypes)
        },
      },
      {
        label: '投诉来源',
        dataIndex: 'source',
        customRender: (data) => selectDictLabel(COMPLAINT_SOURCE, props.rowData?.source),
      },
      {
        label: '投诉状态',
        dataIndex: 'status',
        customRender: (data) => selectDictLabel(COMPLAINT_STATUS, data.status),
      },
    ],
    ali: [
      {
        label: '投诉订单号',
        dataIndex: 'taskId',
      },
      {
        label: '商户名称',
        dataIndex: 'merchantName',
      },
      {
        label: '投诉金额',
        dataIndex: 'complainAmount',
      },
      {
        label: '退款金额',
        dataIndex: 'refundAmount',
      },
      {
        label: '投诉时间',
        dataIndex: 'gmtComplain',
        customRender: (data) => dayjs(data.gmtComplain).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        label: '处理时间',
        dataIndex: 'gmtProcess',
        customRender: (data) => dayjs(data.gmtProcess).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        label: '过期时间',
        dataIndex: 'gmtOverdue',
        customRender: (data) => dayjs(data.gmtOverdue).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        label: '投诉网址',
        dataIndex: 'complainUrl',
      },
      {
        label: '通道类型',
        dataIndex: 'channelTypes',
        customRender: () => {
          return proxy.$smartEnumPlugin.getDescByValue('ZZB_CHANNEL_TYPE_ENUM', props.rowData?.channelTypes)
        },
      },
      {
        label: '投诉来源',
        dataIndex: 'source',
        customRender: (data) => selectDictLabel(COMPLAINT_SOURCE, props.rowData?.source),
      },
      {
        label: '投诉状态',
        dataIndex: 'status',
        customRender: (data) => selectDictLabel(COMPLAINT_STATUS, data.status),
      },
    ],
  })

  const complaintConfig = ref({
    alimini: [
      {
        label: '用户联系方式',
        dataIndex: 'phoneNo',
      },
      {
        label: '投诉原因',
        dataIndex: 'complainReason',
      },
      {
        label: '投诉诉求',
        dataIndex: 'leafCategoryName',
      },
      {
        label: '投诉内容',
        dataIndex: 'content',
      },
      {
        label: '投诉图片',
        dataIndex: 'images',
        customRender: (data) => {
          if (data?.images?.length == 0) return
          let arr = data.images?.map((item) => {
            return h(Image, { width: '50px', height: '50px', src: item })
          })
          return h('div', arr)
        },
      },
    ],
    ali: [
      {
        label: '用户联系方式',
        dataIndex: 'contact',
      },
      {
        label: '投诉内容',
        dataIndex: 'complainContent',
      },
    ],
  })

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {},
    },
    formSource: {
      type: String,
      default: 'alimini', // alimini | ali
    },
  })
  const emit = defineEmits(['update:open', 'ok'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------
  const historyData = ref([])
  // 获取表单信息
  async function getFormInfo(data) {
    const { complaintNo, merchantId } = data
    SmartLoading.show()
    try {
      let res = await apiSource[props.formSource]({ complaintId: complaintNo, merchantId })
      if (res.code === 200) {
        replyForm.value = res.data
        historyData.value = res.data?.replyDetailInfos
      }
    } catch (error) {
      console.error(error)
    }
    SmartLoading.hide()
  }
  // 是否显示
  function show(rowData) {
    getFormInfo(rowData)
  }

  // 回复用户弹窗相关
  const infoForm = {
    complaintId: undefined, //投诉单id
    isRefund: undefined, //是否退款
  }
  const replyForm = ref(cloneDeep(infoForm))

  function onReplyModalClose() {
    replyForm.value = cloneDeep(infoForm)
    openForm.value = false
  }

  // 刷新
  const resh = ref(false)
  function refresh() {
    resh.value = !resh.value
  }
  defineExpose({
    show,
  })
  watch(
    [() => props.rowData, () => props.open, () => resh.value],
    (val) => {
      if (props.open && props.rowData) {
        show(val[0])
      }
    },
    { immediate: true },
  )
</script>
